package com.iwuke.dance.util.independent_edit_text;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;

import androidx.appcompat.widget.AppCompatEditText;

/**
 * @author: 魏从响
 * @date: 2025/10/9
 * 独立的输入框
 */
public class IndependentEditText extends AppCompatEditText {
    private OnPasteListener onPasteListener;

    public interface OnPasteListener {
        void onPaste(String code);
    }

    public IndependentEditText(Context context) {
        super(context);
    }

    public IndependentEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public IndependentEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setOnPasteListener(OnPasteListener listener) {
        this.onPasteListener = listener;
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new InputConnectionWrapper(super.onCreateInputConnection(outAttrs), true) {
            @Override
            public boolean commitText(CharSequence text, int newCursorPosition) {
                if (text != null && text.length() == 6 && text.toString().matches("\\d{6}")) {
                    if (onPasteListener != null) {
                        onPasteListener.onPaste(text.toString());
                        return true;
                    }
                }
                return super.commitText(text, newCursorPosition);
            }
        };
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        if (id == android.R.id.paste) {
            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipboard.hasPrimaryClip()) {
                ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
                String pasteData = item.getText().toString();
                if (pasteData != null && pasteData.matches("\\d{6}")) {
                    if (onPasteListener != null) {
                        onPasteListener.onPaste(pasteData);
                        return true;
                    }
                }
            }
        }
        return super.onTextContextMenuItem(id);
    }
}
